﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VietThinks.Website.Controllers;
using VietThinks.Web.Mvc;

namespace VietThinks.Website.ActionFilter
{
    public class CustomOutputCache : ActionFilterAttribute
    {
        public long Duration { get; set; }
        public string Key { get; set; }
        private bool cacheMiss = false;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            var cached = HttpContext.Current.Cache[string.Format("{0}{1}", Key, filterContext.HttpContext.Request.RawUrl)] as ViewResult;

            if (cached != null)
            {
                filterContext.Result = cached;
            }
            else
            {
                cacheMiss = true;
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            if (!filterContext.Canceled && cacheMiss)
            {
                HttpContext.Current.Cache.Add(string.Format("{0}{1}", Key, filterContext.HttpContext.Request.RawUrl), filterContext.Result, null, DateTime.Now.AddSeconds(Duration), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
            }
        }
    }
}
